package com.toonyoo.eurekaproducer.util;

public class RetryManage {

    private int retryNum = 1;

    private Retry retry;

    private RetryListener retryListener;

    public RetryManage(Retry retry, int retryNum){
        this.retry = retry;
        this.retryNum = retryNum;
    }

    public RetryManage(Retry retry, RetryListener retryListener, int retryNum){
        this.retry = retry;
        this.retryNum = retryNum;
        this.retryListener = retryListener;
    }

    public void call(){
        boolean success = false;
        while (retryNum > 0){
            try {
                if(retry.doTry()){
                    success = true;
                    break;
                }
            }catch (Exception e){
                if(retryListener != null){
                    retryListener.exception(e);
                }else {
                    e.printStackTrace();
                }
            }finally {
                retryNum--;
            }
        }
        if(retryListener != null){
            if(success){
                retryListener.success();
            }else {
                retryListener.fail();
            }
        }
    }

    public int getRetryNum() {
        return retryNum;
    }

    public void setRetryNum(int retryNum) {
        this.retryNum = retryNum;
    }

    public Retry getRetry() {
        return retry;
    }

    public void setRetry(Retry retry) {
        this.retry = retry;
    }

    public RetryListener getRetryListener() {
        return retryListener;
    }

    public void setRetryListener(RetryListener retryListener) {
        this.retryListener = retryListener;
    }
}
